import { ref, computed } from "vue";
import { defineStore } from "pinia";

export interface MaterialImage {
  id: string;
  url: string;
  name: string;
  originalName: string;
  tags: string[];
  uploadTime: number;
  usedCount: number;
  isFavorite?: boolean;
}

export interface MaterialHistory {
  id: string;
  type: "caption" | "expand";
  imageId: string;
  content: string;
  time: number;
}

// 生成测试数据
function generateTestData(): MaterialImage[] {
  const testImages: MaterialImage[] = [];
  const tags = [
    "产品",
    "运动",
    "红色",
    "白色",
    "黑色",
    "电子产品",
    "办公",
    "工作",
    "室内",
    "数据",
    "分析",
    "报表",
    "户外",
    "雪",
    "时尚",
    "商务",
    "科技",
    "自然",
    "建筑",
    "美食",
  ];
  const names = [
    "运动鞋产品图",
    "手表展示",
    "耳机产品",
    "办公环境",
    "数据看板",
    "滑雪运动",
    "笔记本电脑",
    "咖啡杯",
    "建筑外观",
    "自然风景",
    "时尚服装",
    "商务会议",
    "科技设备",
    "美食摄影",
    "汽车展示",
    "家居用品",
    "户外装备",
    "艺术设计",
    "医疗设备",
    "教育场景",
    "旅游景点",
    "工业设备",
    "农业产品",
    "娱乐设施",
  ];

  for (let i = 1; i <= 100; i++) {
    const randomTags = tags
      .sort(() => Math.random() - 0.5)
      .slice(0, Math.floor(Math.random() * 4) + 1);
    const randomName =
      names[Math.floor(Math.random() * names.length)] + ` ${i}`;
    const randomTime =
      Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000; // 最近30天内
    const randomCount = Math.floor(Math.random() * 50) + 1;

    testImages.push({
      id: i.toString(),
      url: `https://picsum.photos/400/300?random=${i}`,
      name: randomName,
      originalName: `${randomName}.jpg`,
      tags: randomTags,
      uploadTime: randomTime,
      usedCount: randomCount,
      isFavorite: Math.random() > 0.8, // 20% 概率收藏
    });
  }

  return testImages;
}

export const useMaterialStore = defineStore("material", () => {
  // 素材图片列表
  const images = ref<MaterialImage[]>(generateTestData());
  // 标签列表
  const tags = ref<string[]>([]);
  // 历史记录
  const history = ref<MaterialHistory[]>([]);
  // 选中的图片ID列表 - 默认不选中任何图片
  const selectedImageIds = ref<string[]>([]);
  // 用于页面间传递的选中图片（如文案生成、图片扩展等）
  const selectedImageForAction = ref<MaterialImage | null>(null);

  // 计算属性：按标签分组
  const imagesByTag = computed(() => {
    const map: Record<string, MaterialImage[]> = {};
    images.value.forEach(img => {
      img.tags.forEach(tag => {
        if (!map[tag]) map[tag] = [];
        map[tag].push(img);
      });
    });
    return map;
  });

  // 计算属性：选中的图片
  const selectedImages = computed(() => {
    return images.value.filter(img => selectedImageIds.value.includes(img.id));
  });

  // 添加图片
  function addImages(newImages: MaterialImage[]) {
    images.value.push(...newImages);
  }

  // 删除图片
  function deleteImage(imageId: string) {
    const index = images.value.findIndex(img => img.id === imageId);
    if (index > -1) {
      images.value.splice(index, 1);
      // 如果删除的是当前选中的图片，清除选中状态
      if (selectedImageForAction.value?.id === imageId) {
        selectedImageForAction.value = null;
      }
    }
  }

  // 添加标签
  function addTag(tag: string) {
    if (!tags.value.includes(tag)) tags.value.push(tag);
  }

  // 添加历史
  function addHistory(record: MaterialHistory) {
    history.value.unshift(record);
  }

  // 清空历史
  function clearHistory() {
    history.value = [];
  }

  // 选中图片
  function selectImage(imageId: string) {
    if (!selectedImageIds.value.includes(imageId)) {
      selectedImageIds.value.push(imageId);
    }
  }

  // 取消选中图片
  function unselectImage(imageId: string) {
    const index = selectedImageIds.value.indexOf(imageId);
    if (index > -1) {
      selectedImageIds.value.splice(index, 1);
    }
  }

  // 切换图片选中状态
  function toggleImageSelection(imageId: string) {
    const index = selectedImageIds.value.indexOf(imageId);
    if (index > -1) {
      selectedImageIds.value.splice(index, 1);
    } else {
      selectedImageIds.value.push(imageId);
    }
  }

  // 全选图片
  function selectAllImages(imageIds: string[]) {
    selectedImageIds.value = [...imageIds];
  }

  // 清空选中
  function clearSelectedImages() {
    selectedImageIds.value = [];
  }

  // 设置用于页面间传递的选中图片
  function setSelectedImageForAction(image: MaterialImage) {
    selectedImageForAction.value = image;
  }

  // 获取用于页面间传递的选中图片
  function getSelectedImageForAction() {
    return selectedImageForAction.value;
  }

  // 清除用于页面间传递的选中图片
  function clearSelectedImageForAction() {
    selectedImageForAction.value = null;
  }

  return {
    images,
    tags,
    history,
    selectedImageIds,
    selectedImages,
    selectedImageForAction,
    imagesByTag,
    addImages,
    deleteImage,
    addTag,
    addHistory,
    clearHistory,
    selectImage,
    unselectImage,
    toggleImageSelection,
    selectAllImages,
    clearSelectedImages,
    setSelectedImageForAction,
    getSelectedImageForAction,
    clearSelectedImageForAction,
  };
});
